<?php

// +----------------------------------------------------------------------
// | WeChatDeveloper
// +----------------------------------------------------------------------
// | 版权所有 2014~2018 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/WeChatDeveloper
// +----------------------------------------------------------------------

namespace Itdashu\SwoftThirdPartyService\Service\WeMini;

use Itdashu\SwoftThirdPartyService\Service\WeChat\Contracts\BasicWeChat;
use Itdashu\SwoftThirdPartyService\Service\WeChat\Exceptions\InvalidDecryptException;
use Itdashu\SwoftThirdPartyService\Service\WeChat\Exceptions\InvalidResponseException;
use Itdashu\SwoftThirdPartyService\Service\Base\Tools;
use Itdashu\SwoftThirdPartyService\Service\WeMini\Crypt\WxBizDataCrypt;


/**
 * 数据加密处理
 * Class Crypt
 * @package WeMini
 */
class Crypt extends BasicWeChat
{

  /**
   * 数据签名校验
   * @param string $iv
   * @param string $sessionKey
   * @param string $encryptedData
   * @return mixed
   */
  public function decode($iv, $sessionKey, $encryptedData)
  {
    $pc = new WxBizDataCrypt($this->config->get('appid'), $sessionKey);
    $errCode = $pc->decryptData($encryptedData, $iv, $data);
    if ((string)$errCode === '0') {
      return json_decode($data, true);
    }
    return false;
  }

  /**
   * 登录凭证校验
   * @param string $code 登录时获取的 code
   * @return mixed
   * @throws \Itdashu\SwoftThirdPartyService\Service\WeChat\Exceptions\LocalCacheException
   */
  public function session($code)
  {
    $appId = $this->config->get('appid');
    $secret = $this->config->get('appsecret');
    $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appId}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
    return json_decode(Tools::get($url), true);
  }

  /**
   * 换取用户信息
   * @param string $code 用户登录凭证（有效期五分钟）
   * @param string $iv 加密算法的初始向量
   * @param string $encryptedData 加密数据( encryptedData )
   * @return array
   * @throws InvalidDecryptException
   * @throws InvalidResponseException
   * @throws \Itdashu\SwoftThirdPartyService\Service\WeChat\Exceptions\LocalCacheException
   */
  public function userInfo(string $code, string $iv, string $encryptedData): array
  {
    $result = $this->session($code);
    if (empty($result['session_key'])) {
      throw new InvalidResponseException('Code 换取 SessionKey 失败', 403);
    }
    $userInfo = $this->decode($iv, $result['session_key'], $encryptedData);
    if (empty($userInfo)) {
      throw new InvalidDecryptException('用户信息解析失败', 403);
    }
    return array_merge($result, $userInfo);
  }

  /**
   * 用户支付完成后，获取该用户的 UnionId
   * @param string $openid 支付用户唯一标识
   * @param null|string $transactionId 微信支付订单号
   * @param null|string $mch_id 微信支付分配的商户号，和商户订单号配合使用
   * @param null|string $outTradeNo 微信支付商户订单号，和商户号配合使用
   * @return array|mixed
   * @throws InvalidResponseException
   * @throws \Itdashu\SwoftThirdPartyService\Service\WeChat\Exceptions\LocalCacheException
   */
  public function getPaidUnionId(string $openid, $transactionId = null, $mch_id = null, $outTradeNo = null)
  {
    $url = "https://api.weixin.qq.com/wxa/getpaidunionid?access_token=ACCESS_TOKEN&openid={$openid}";
    if ($mch_id === null) {
      $url .= "&mch_id={$mch_id}";
    }
    if ($outTradeNo === null) {
      $url .= "&out_trade_no={$outTradeNo}";
    }
    if ($transactionId === null) {
      $url .= "&transaction_id={$transactionId}";
    }
    $this->registerApi($url, __FUNCTION__, func_get_args());
    return $this->callGetApi($url);
  }
}